package com.site.action;

import java.io.IOException;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.site.dto.backend.system.AuthorityBizBean;
import com.site.dto.backend.system.RoleBizBean;
import com.site.dto.backend.system.UsersBizBean;
import com.site.service.backend.system.UsersService;
import com.site.util.CodeUtils;
import com.site.util.base.action.BackendBaseAction;
import com.site.util.base.dto.User;
import com.site.util.constant.Constants;
import com.site.util.exception.ApplicationException;

/**
 * 后台用户登录
 * @author lee 2012-10-09
 *
 */
public class LoginAction extends BackendBaseAction {

	private static final long serialVersionUID = 6919839379782628115L;

	private Log log = LogFactory.getLog(LoginAction.class);

	private User user;
	
	private String rand;
	
	private String rd;
 
	private String error = "false";
	private String errorMsg; 
 
	private UsersService usersService;
	
	/**
	 * 登录
	 * 
	 * @return
	 * @throws ApplicationException
	 * @throws IOException
	 */
	public String login() throws ApplicationException, IOException {
		if (!check()) {
			rand="";
			error = "true";
			return INPUT;
		}
		// 取得用户真实IP
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0
				|| "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		String userName = user.getUserName();
		UsersBizBean usersBizBean = (UsersBizBean)usersService.loadUserByUsername(userName);
		if (usersBizBean == null) {
			
			error = "true";
			errorMsg = "ERROR0024";
			log.info(userName + "登陆失败，用户不存在!");
			return INPUT;
			
		} else {
			
			if(null != usersBizBean && Constants.COMM_Y.equals(usersBizBean.getStatus())){
				error = "true";
				errorMsg = "ERROR0025";
				log.info(userName + "  登录失败，用户被锁定!");
				return INPUT;
			}
			
			try {
				String securedpwd = CodeUtils.md5Digest(user.getPassword());
				if (!usersBizBean.getPassWord().trim().equals(securedpwd)) {
					error = "true";
					errorMsg = "ERROR0026";
					log.info(userName + "登陆失败，密码错误!");
					if("true".equals(error)) {
						return INPUT;
					}
				}
				log.info("来自（IP）："+ip+",的 "+userName + "用户, 登陆成功!");
				user.setPassword(null);
				// 登录成功 ，添加用户相关信息
				user.setId(usersBizBean.getUserId().intValue());
				user.setUserRealName(usersBizBean.getRealName());
				// 添加用户权限
				Set<RoleBizBean> roles = usersBizBean.getRoleSet();
				if(null != roles && roles.size() > 0){
					for (RoleBizBean role : roles) {
						Set<AuthorityBizBean> auths = role.getAuthoritySet();
						if(null != auths && auths.size() > 0){
							for (AuthorityBizBean authBean : auths) {
								user.getAuthSet().add(authBean);
							}
						}
					}
				}
				keepCurrentUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}

	private boolean check() {
		boolean result = true;

		String randCode=(String)sessionMap.get(Constants.RANDOM_CODE);
		if(rand==null||rand.isEmpty()) {
			 super.addActionError("请输入随机码");
			 errorMsg = "ERROR0038";
			 result = false;
		} else if(randCode==null) {
			 super.addActionError("随机码过期，请重试");
			 errorMsg = "ERROR0039";
			 result = false;
		} else if(!randCode.equals(rand)) {
			 super.addActionError("随机码错误");
			 errorMsg = "ERROR0040";
			 result = false;
		} else if (user.getUserName().isEmpty()) {
			super.addActionError("用户名不能为空");
			errorMsg = "ERROR0041";
			result = false;
		} else if (user.getPassword().isEmpty()) {
			super.addActionError("密码不能为空");
			errorMsg = "ERROR0042";
			result = false;
		}
		return result;
	}

	/**
	 * 退出和注销
	 * 
	 * @return
	 * @throws 
	 */
	public String logout() {
		user = getCurrentUser();
		if (user != null) {
			String userName = user.getUserName();
			log.info(userName + " 退出/注销成功!");
		}
		if (user == null) {
			return INPUT;
		}
		request.getSession().invalidate();
		return INPUT;
	}
	
	@Resource
	public void setUsersService(UsersService usersService) {
		this.usersService = usersService;
	}
	public String getRand() {
		return rand;
	}
	public void setRand(String rand) {
		this.rand = rand;
	}
	public String getError() {
		return error;
	}
	public void setError(String error) {
		this.error = error;
	}
	public String getErrorMsg() {
		return errorMsg;
	}
	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}

	public UsersService getUsersService() {
		return usersService;
	}
	public String getRd() {
		return rd;
	}
	public void setRd(String rd) {
		this.rd = rd;
	}
}
